<template>
  <div class="order-con table-gl-w">
    <div class="search-w">
      <div style="display: flex" v-if="currentIndex == 'UNSHIPPED_TOCHECK'">
        <div @click="cutStatus(item, index)" :class="['tag-item', statusCurrentIndex == index ? 'tag-item-active' : '']" v-for="(item, index) of statusList">{{ item.label }}({{ item.num }})</div>
      </div>
      <FilterTable :filterItem="selFilterItem" ref="filterTable" :maxNum="statusCurrentIndex != 11 ? 4 : 0" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="refresh">
        <template #headerRight>
          <a-popover content="导出库存">
            <a-button type="text" style="font-size: 16px; color: #141840">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover>
        </template>
        <template #headerLeft v-if="currentIndex == 'VIR_FBM_ALL' && statusCurrentIndex != 11">
          <a-button class="gray-outline" style="margin-right: 5px" @click="showAddModal('add')" v-if="$authPass('oms.order.saveOrUpdateOrder')">手工录入订单</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" @click="setTag('mul')">设置标签</a-button>
          <a-button type="text" style="margin-right: 5px" @click="copy">一键复制订单号</a-button>
        </template>
        <template #headerLeft v-if="currentIndex == 'UNSHIPPED_TOCHECK' && statusCurrentIndex != 11">
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 5 && $authPass('oms.order.syncProductRelated')" :loading="syncLoading" @click="updateUser">批量更新SKU和销售员</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 5 && $authPass('oms.order.updateItemPack')" @click="setPack">设置包装</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 5 && $authPass('oms.order.updatePackageWarehouse')" @click="matchHouse">指定发货仓</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" @click="setTag('mul')">设置标签</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 4 && statusCurrentIndex != 5 && $authPass('oms.order.createOrderShip')" @click="showLogisticsOrderModal">物流下单</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 5" @click="setTariffInfo">设置报关信息</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" v-if="statusCurrentIndex != 4 && statusCurrentIndex != 5 && $authPass('oms.order.submitWarehouse')" @click="batchSubmit">提交仓库</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" :loading="FBMLoading" @click="syncFBMorder">一键同步订单</a-button>
          <a-button type="text" style="margin-right: 5px" @click="copy">一键复制订单号</a-button>
        </template>
        <template #headerLeft v-if="currentIndex == 'UNSHIPPED_TOSHIP' && statusCurrentIndex != 11">
          <a-button class="gray-outline" style="margin-right: 5px" @click="setTag('mul')">设置标签</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" @click="showLogisticsOrderModal" v-if="$authPass('oms.order.createOrderShip')">物流下单</a-button>
          <a-button class="gray-outline" style="margin-right: 5px" @click="setTariffInfo">设置报关信息</a-button>
          <a-button type="text" style="margin-right: 5px" @click="copy">一键复制订单号</a-button>
        </template>
        <template #headerLeft v-if="statusCurrentIndex == 11">
          <a-button class="gray-outline" @click="mergeOrder.cancelMerge('mul')">取消合并</a-button>
        </template>
        <template #tableBody>
          <a-spin :loading="loading" style="width: 100%; height: 100%">
            <div style="height: 100%" v-show="statusCurrentIndex != 11">
              <Table v-if="dataList.length > 0" :getList="getList" :orderStatus="currentIndex" :showAddModal="showAddModal" :statusCurrentIndex="statusCurrentIndex" :parentSetTag="setTag" ref="table" :dataList="dataList" v-model="selectRow" />
              <a-empty v-else />
            </div>
            <div style="height: 100%" v-show="statusCurrentIndex == 11">
              <MergeOrder ref="mergeOrder" :statusCurrentIndex="statusCurrentIndex" :searchValue="searchValue" />
            </div>
          </a-spin>
        </template>
      </TableWrap>
      <div class="pagination-footer" v-if="statusCurrentIndex != 11">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <MatchWarehouse ref="matchWarehouse" type="order" :selectRow="selectRow" @save="saveWarehouse" />
  <Tag ref="tag" :dataList="tagList" @save="saveTag" type="oms" />
  <Pack ref="pack" :selectRow="selectRow" :ids="idList" @save="getList" />
  <LogisticsOrder ref="logisticsOrder" type="order" :selectRow="selectRow" @save="getList" />
  <TariffInfo ref="tariffInfo" :selectRow="selectRow" @save="getList" />
  <SubmitForDelivery ref="submitForDelivery" type="order" :selectRow="selectRow" @save="getList" />
  <HandleAddOrder ref="handleAddOrderModal" :type="addModalType" :id="id" @save="sizeChange(20)" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, defineAsyncComponent, watch } from 'vue'
  import { getShopMarketAll } from '@/api/base'
  import { findShopListByShare, findWarehouseListByParam } from '@/api/warehouse'
  import { fbmPage, syncProductRelated, addFBMorderTagBatch, countOrderTagNum, cancelFBMorderTagBatch, syncFBAOrders, tagList, findShopMarketByParam } from '@/api/order'
  import { getOrganizesUser } from '@/api/system'
  import { countriesOptions } from '@/utils/countries'
  import { Message, Modal } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import MatchWarehouse from './matchWarehouse.vue'
  import Tag from '../../components/tag/tagList.vue'
  import Table from './table.vue'
  import MergeOrder from './mergeOrder.vue'
  import Pack from './pack.vue'
  import LogisticsOrder from './logisticsOrder.vue'
  import TariffInfo from './tariffInfo.vue'
  import SubmitForDelivery from './submitForDelivery.vue'
  import HandleAddOrder from './handleAddOrder.vue'
  import useClipboard from 'vue-clipboard3'
  import _ from 'lodash-es'

  export default defineComponent({
    components: {
      FilterTable,
      TableWrap,
      Table,
      MatchWarehouse,
      Tag,
      Pack,
      LogisticsOrder,
      TariffInfo,
      MergeOrder,
      SubmitForDelivery,
      HandleAddOrder,
    },
    props: ['currentIndex', 'orderTagNum', 'getNum'],
    setup(props: any, { emit }) {
      const table = ref()
      const matchWarehouse = ref()
      const tag = ref()
      const pack = ref()
      const logisticsOrder = ref()
      const tariffInfo = ref()
      const mergeOrder = ref()
      const submitForDelivery = ref()
      const filterTable = ref()
      const handleAddOrderModal = ref()
      const { toClipboard } = useClipboard()

      const data: any = reactive({
        filterItem: [
          {
            key: 'marketplaceIdList',
            label: '站点',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'sellerMarketId',
            label: '店铺',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },

          {
            type: 'input_keyword',
            key: 'productSkuList',
            keyItems: [
              { label: 'SKU', value: 'productSkuList' },
              { label: 'MSKU', value: 'mskuList' },
              { label: '商品名称', value: 'productNameList' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 160,
            isMultiple: true,
          },

          {
            type: 'input_keyword',
            key: 'platOrderNumberList',
            keyItems: [
              { label: '平台单号', value: 'platOrderNumberList' },
              { label: '申购单号', value: 'purchaseNumber' },
            ],
            keyWidth: '120',
            value: ref(),
            placeholder: '请输入',
            label: '订单号',
            width: 160,
            isMultiple: true,
          },

          {
            key: 'orderTagCodeList',
            label: '订单标签',
            value: ref(),
            type: 'select',
            // width: '140px',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },

          {
            key: 'salerIdList',
            label: '销售员',
            value: ref(),
            type: 'select',
            // width: '140px',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'keyword_date_range',
            key: 'gmtPurchase',
            keyItems: [
              { label: '下单时间(+8)', value: 'gmtPurchase' },
              { label: '下单时间(+0)', value: 'gmtPurchase0' },
              { label: '创建时间', value: 'gmtCreate' },
              { label: '承诺发货时间', value: 'gmtLatestShip' },
              { label: '实际发货时间', value: 'gmtShip' },
              { label: '标发货时间', value: 'gmtVirtualShip' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: '下单时间(+8)',
            width: 200,
          },
          {
            key: 'warehouseCodeList',
            label: '发货仓',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'trackingNumberList',
            label: '物流跟踪号',
            value: ref(),
            type: 'input_search',
            width: '100%',
          },
          {
            key: 'isCustom',
            label: '是否定制',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '是定制', value: true },
              { label: '否定制', value: false },
            ],
          },
          {
            key: 'isTransparency',
            label: '是否透明计划',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '是透明计划', value: true },
              { label: '否透明计划', value: false },
            ],
          },
          {
            key: 'isVirtualShip',
            label: '虚假发货',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '是', value: true },
              { label: '否', value: false },
            ],
          },
          {
            key: 'gmtPay',
            label: '订单金额',
            value: ref(),
            type: 'input_search',
            width: '100%',
          },
          {
            key: 'shipRemainDay',
            label: '发货剩余天数',
            value: ref(),
            type: 'input_search',
            width: '100%',
          },
          {
            key: 'countryCodeList',
            label: '收货国家',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: countriesOptions.map((e: any) => {
              e.label = `${e.name}-${e.short}`
              e.value = e.short
              return e
            }),
            attrs: {
              'allow-search': true,
            },
          },
        ],
        selFilterItem: [],
        tagList: [],
        statusList: [
          { label: '全部', value: '', num: props.orderTagNum },
          { label: 'SKU未配对', value: 'NOT_MATCH_SKU', num: '222' },
          { label: '发货仓未匹配', value: 'NOT_MATCH_WAREHOUSE', num: '333' },
          { label: '买家留言', value: 'HAS_BUYER_MESSAGE', num: '333' },
          { label: '地址错误', value: 'ADDRESS_ERROR', num: '333' },
          { label: '禁止处理', value: 'STOP_HAND', num: '333' },
          { label: '撤回改单', value: 'ROLLBACK_ORDER', num: '333' },
          { label: '未匹配物流', value: 'NOT_MATCH_EXPRESS', num: '333' },
          { label: '物流下单失败', value: 'CREATE_ORDER_SHIP_ERROR', num: '333' },
          { label: '手工录入订单', value: 'OFFLINE_ORDER', num: '333' },
          { label: '缺货', value: 'STOCK_NOT_ENOUGH', num: '333' },
          { label: '待合并', value: 'TOBE_COMBINE', num: '333' },
        ],
        statusCurrentIndex: 0,
        dataList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        expandable: {},
        loading: false,
        syncLoading: false,
        FBMLoading: false,
        isCollapse: false,
        info: {
          type: 'in',
          id: '',
        },
        id: '',
        searchValue: {},
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        selectRow: [],
        orderSystemTagCode: '',
        searchStatusList: 'VIR_FBM_ALL',
        addModalType: 'add',
        idList: [],
      })

      if (data.statusCurrentIndex != 11) {
        data.selFilterItem = data.filterItem
      }

      const searchByVal = (info: any) => {
        let obj = _.cloneDeep(info)
        data.searchValue = obj
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }

        // for (const key in obj) {
        //   if (key == 'date' && obj[key]) {
        //     data.searchValue.startDate = `${obj[key][0]} 00:00:00`
        //     data.searchValue.endDate = `${obj[key][1]} 23:59:59`
        //   } else {
        //     data.searchValue[key] = obj[key]
        //   }
        // }

        if (data.statusCurrentIndex != 11) {
          data.pageNation.pageNum = 1
          getList()
        }
      }
      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const getMarketList = async () => {
        const res = await getShopMarketAll()
        let arr = res.data.map((e: any) => {
          e.label = e.marketplaceName
          e.value = e.marketplaceId
          return e
        })
        data.filterItem[0].optionItems = arr
      }

      const getShopListByShare = async () => {
        const res = await findShopMarketByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.sellerMarketId
        })
        data.filterItem[1].optionItems = arr
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let arr = res.data?.records
          arr.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[5].optionItems = arr
        }
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.warehouseName
          e.value = e.warehouseCode
        })
        data.filterItem[7].optionItems = arr
      }

      // 订单标签
      const getOrderTag = async () => {
        const res: any = await tagList()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.name
          e.value = e.code
        })
        data.filterItem[4].optionItems = arr
      }

      const matchHouse = () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        matchWarehouse.value.visible = true
      }
      const setTag = (type: string, item: any) => {
        if (data.selectRow.length <= 0 && type == 'mul') {
          return Message.error('请选择需要操作的数据')
        }

        if (type == 'mul') {
          data.selectRow.forEach((e: any) => {
            data.tagList = [...data.tagList, ...e.tagList]
          })
        } else {
          data.tagList = item.tagList
          data.selectRow.push(item)
        }

        tag.value.visible = true
      }
      const setPack = () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        data.idList = []
        data.selectRow.forEach((e: any) => {
          e.packageList.forEach((el: any) => {
            el.packageItemList.forEach((ell: any) => {
              data.idList.push(ell.id)
            })
          })
        })

        pack.value.visible = true
      }
      const showLogisticsOrderModal = () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        logisticsOrder.value.visible = true
      }
      const setTariffInfo = () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        tariffInfo.value.visible = true
      }

      const batchSubmit = () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }

        submitForDelivery.value.visible = true

        // Modal.confirm({
        //   title: '提示',
        //   content: '是否要批量提交？',
        //   okText: '确认',
        //   cancelText: '取消',
        //   onOk: async () => {
        //     let arr = data.selectRow.map((e: any) => e.id)
        //     const res: any = await submitShip(arr)
        //     if (res.code == 'SUCCESS') Message.success('提交订单成功')
        //     getList()
        //   },
        // })
      }

      const resetSelRow = () => {
        table.value ? (table.value.checkIdList = []) : ''
        data.selectRow = []
      }

      const cutStatus = (item: any, index: number) => {
        data.statusCurrentIndex = index
        data.orderSystemTagCode = item.value
        if (index != 11) {
          data.selFilterItem = data.filterItem
          data.pageNation.pageNum = 1
          getList()
        } else {
          data.selFilterItem = data.filterItem.slice(0, 7)
        }
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          statusList: data.searchStatusList,
          orderSystemTagCode: data.orderSystemTagCode,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        // data.loading = false
        const res = await fbmPage(params)
        let arr = res?.data?.records || []
        data.dataList = arr
        data.pageNation.total = res?.data?.total
        data.loading = false
        resetSelRow()
      }

      const updateUser = async () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        let arr = data.selectRow.map((e: any) => e.id)
        data.syncLoading = true
        const res: any = await syncProductRelated(arr)
        if (res.code == 'SUCCESS') {
          Message.success('更新成功')
          resetSelRow()
        }
        data.syncLoading = false
      }
      const syncFBMorder = async () => {
        if (data.selectRow.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        let arr = data.selectRow.map((e: any) => e.id)
        data.FBMLoading = true
        const res: any = await syncFBAOrders(arr)
        if (res.code == 'SUCCESS') {
          Message.success('同步成功')
          resetSelRow()
        }
        data.FBMLoading = false
      }

      const saveTag = async (ids: Array<string>, type: string) => {
        let params = {
          orderIdList: data.selectRow.map((e: any) => e.id),
          // tagIdList: ids,
          tagCodeList: ids,
        }

        let res: any = {}

        if (type == 'add') {
          res = await addFBMorderTagBatch(params)
        } else {
          res = await cancelFBMorderTagBatch(params)
        }

        if (res.code == 'SUCCESS') {
          type == 'add' ? Message.success('添加标签成功') : Message.success('删除标签成功')
          tag.value.visible = false
          resetSelRow()
          setTimeout(() => {
            getList()
          }, 1000)
        }
      }

      const copy = async () => {
        let arr = data.dataList.map((e: any) => e.platformOrderNumber)
        try {
          // 复制
          await toClipboard(arr.join('\n'))
          Message.success('复制成功')
          // 复制成功
        } catch (e) {
          // 复制失败
        }
      }

      const saveWarehouse = () => {
        getList()
        resetSelRow()
      }

      const refresh = () => {
        props.getNum()
        getOrderTagNum()
        if (data.statusCurrentIndex != 11) {
          getList()
        } else {
          mergeOrder.value.getList()
        }
      }

      const getOrderTagNum = async () => {
        const res: any = await countOrderTagNum()
        data.statusList[1].num = res?.data?.notMatchSku || 0
        data.statusList[2].num = res?.data?.notMatchWarehouse || 0
        data.statusList[3].num = res?.data?.hasBuyerMessage || 0
        data.statusList[4].num = res?.data?.addressError || 0
        data.statusList[5].num = res?.data?.stopHand || 0
        data.statusList[6].num = res?.data?.rollbackOrder || 0
        data.statusList[7].num = res?.data?.notMatchExpress || 0
        data.statusList[8].num = res?.data?.createOrderShipError || 0
        data.statusList[9].num = res?.data?.offlineOrder || 0
        data.statusList[10].num = res?.data?.stockNotEnough || 0
        data.statusList[11].num = res?.data?.tobeCombine || 0
      }

      const showAddModal = (type: string, item?: any) => {
        data.addModalType = type
        if (type == 'edit') data.id = item.id
        handleAddOrderModal.value.visible = true
      }

      watch(
        () => props.currentIndex,
        (val) => {
          setTimeout(() => {
            data.statusCurrentIndex = 0
            data.orderSystemTagCode = ''
            data.searchStatusList = val
            data.pageNation.pageNum = 1
            getList()
          }, 180)
        }
      )

      watch(
        () => props.orderTagNum,
        (val) => {
          data.statusList[0].num = val
        }
      )

      getMarketList()
      getOrderTagNum()
      getShopListByShare()
      getUSerList()
      getWareHouseList()
      getOrderTag()
      getList()
      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        mergeOrder,
        getList,
        table,
        matchHouse,
        matchWarehouse,
        tag,
        setTag,
        cutStatus,
        setPack,
        pack,
        logisticsOrder,
        showLogisticsOrderModal,
        setTariffInfo,
        tariffInfo,
        updateUser,
        saveTag,
        copy,
        batchSubmit,
        syncFBMorder,
        saveWarehouse,
        refresh,
        submitForDelivery,
        filterTable,
        showAddModal,
        handleAddOrderModal,
      }
    },
  })
</script>

<style lang="less" scoped>
  .order-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;

    :deep(.arco-table-cell-align-left) {
      padding: 0 !important;
    }

    .item-detail {
      min-height: 56px;
      width: 100%;
      border-bottom: 1px solid #e5e6eb;
    }
  }

  .tag-item {
    // float: left;
    padding: 5px 5px;
    margin: 0px 0 10px 0;
    border: 1px solid var(--color-border);
    margin-right: 10px;
    border-radius: 3px;
    font-size: 12px;
    cursor: pointer;
    user-select: none;
  }

  .tag-item-active {
    border: 1px solid #615dff;
    color: #615dff;
  }
</style>
